package cn.tedu.crm.dept.service.impl;

import cn.tedu.crm.dept.mapper.DeptMapper;
import cn.tedu.crm.dept.pojo.dto.DeptParam;
import cn.tedu.crm.dept.pojo.dto.DeptQuery;
import cn.tedu.crm.dept.pojo.entity.Dept;
import cn.tedu.crm.dept.pojo.vo.DeptVO;
import cn.tedu.crm.dept.service.DeptService;
import cn.tedu.crm.operatelog.loggable.Loggable;
import cn.tedu.crm.operatelog.loggable.OperationModule;
import cn.tedu.crm.operatelog.loggable.OperationType;
import cn.tedu.crm.user.mapper.UserMapper;
import cn.tedu.crm.user.pojo.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Slf4j
@Service
public class DeptServiceImpl implements DeptService{

    @Autowired
    DeptMapper deptMapper;
    @Autowired
    UserMapper userMapper;


    @Override
    public List<DeptVO> selectDept(DeptQuery query) {
        log.debug("查询部门业务:{}",query);
        return deptMapper.selectDept(query);
    }


    @Override
    @Loggable(module = OperationModule.ORGANIZATION_MANAGEMENT,type = OperationType.INSERT_UPDATE)
    public void addDept(DeptParam deptParam) {
        log.debug("添加部门业务:{}",deptParam);
        Dept dept = new Dept();
        BeanUtils.copyProperties(deptParam,dept);
        if (dept.getId() == null){
            deptMapper.insert(dept);
            log.debug("添加部门业务:{}",dept);
        }else {
            deptMapper.updateById(dept);
        }

        User user = new User();
        BeanUtils.copyProperties(deptParam,user);
        user.setDeptId(dept.getId());
        if (user.getDeptId() == null){
            userMapper.insert(user);
            log.debug("添加用户表部门业务:{}",user);
        }else {
            userMapper.updateById(user);
        }
    }

    @Override
    @Loggable(module = OperationModule.ORGANIZATION_MANAGEMENT,type = OperationType.DELETE)
    public void deleteDept(Long id) {
        log.debug("删除部门业务:{}",id);
        deptMapper.deleteById(id);
    }

    @Override
    public DeptVO selectById(Long id) {
        log.debug("根据id查询部门信息业务:{}", id);
        Dept dept = deptMapper.selectById(id);
        if(dept != null){
            DeptVO deptVO = new DeptVO();
            BeanUtils.copyProperties(dept,deptVO);
            return deptVO;
        }
        return null;
    }




}




